package com.bluefuture.modules.app.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bluefuture.common.exception.GlobalException;
import com.bluefuture.common.utils.ResultEnum;
import com.bluefuture.common.utils.ResultVo;
import com.bluefuture.common.utils.ResultVoUtil;
import com.bluefuture.modules.app.entity.UserEntity;
import com.bluefuture.modules.app.form.*;
import com.bluefuture.modules.app.service.UserComplaintService;
import com.bluefuture.modules.app.service.UserService;
import com.bluefuture.modules.app.service.impl.EmailService;
import com.bluefuture.modules.app.service.impl.SmsService;
import com.bluefuture.modules.app.vo.UserVO;
import com.bluefuture.modules.sys.security.user.SecurityUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 注册
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api(tags = "APP用户登录注册接口")
@Slf4j
public class AppUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private UserComplaintService userComplaintService;


    @PostMapping("users")
    @ApiOperation(value = "获取首页用户")
    public ResultVo<Page<UserVO>> userList(@Valid @RequestBody UserQueryParam userQueryParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error(bindingResult.getFieldError().getDefaultMessage());
            throw new GlobalException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        Page<UserVO> userVOPage = userService.userList(userQueryParam);
        return ResultVoUtil.success(userVOPage);

    }

    @GetMapping("allUsers")
    public ResultVo<List<UserVO>> allUsers(){
        List<UserEntity> userEntities = userService.allUsers();
        return ResultVoUtil.success(userEntities.stream().map(e -> {
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(e, vo);
            return vo;
        }).collect(Collectors.toList()));
    }

    @PostMapping("complaint")
    @ApiOperation(value = "用户拉黑投诉接口")
    public ResultVo complaint(@Valid @RequestBody ComplaintForm complaintForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error(bindingResult.getFieldError().getDefaultMessage());
            throw new GlobalException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        userComplaintService.saveComplaint(complaintForm);
        return ResultVoUtil.success();
    }

    @PostMapping("register")
    @ApiOperation(value = "用户注册接口，成功返回0，参数有误返回1000,手机号已注册返回1026,邮箱验证码校验失败返回1003，手机验证码校验失败返回1001")
    public ResultVo<UserVO> register(@Valid @RequestBody RegisterForm userRegisterForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error(bindingResult.getFieldError().getDefaultMessage());
            throw new GlobalException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        UserVO userVO = userService.register(userRegisterForm);
        return ResultVoUtil.success(userVO);
    }

    @GetMapping("test")
    public String test() {
        System.out.println(SecurityUser.getUserId());
        return "test";
    }

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation(value = "用户登录接口，成功返回0，账号密码错误返回1000")
    public ResultVo<UserVO> login(@Valid @RequestBody LoginForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error(bindingResult.getFieldError().getDefaultMessage());
            throw new GlobalException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }

        return ResultVoUtil.success(userService.login(form));
    }

    /**
     * 登录
     */
    @PostMapping("update")
    @ApiOperation(value = "用户更新接口，成功返回0")
    public ResultVo update(@Valid @RequestBody UpdateForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error(bindingResult.getFieldError().getDefaultMessage());
            throw new GlobalException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        userService.update(form);
        return ResultVoUtil.success();
    }

    @GetMapping("verifyCode")
    @ApiOperation(value = "获取验证码，成功返回0，失败返回1001")
    public ResultVo verifyCode(@RequestParam("contact") String contact) {
        String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        if (contact.matches(EMAIL_REGEX)) {
            emailService.sendVerifyCode(contact);
        } else {
            smsService.sendVerifyCode(contact);
        }
        return ResultVoUtil.success();
    }

    @PostMapping("code/verify")
    @ApiOperation(value = "验证码校验，成功返回0，失败返回1002")
    public ResultVo checkVerifyCode(@RequestParam("contact") String contact, @RequestParam("code") String code) {
        String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        if (contact.matches(EMAIL_REGEX)) {
            emailService.checkVerifyCode(contact, code);
        } else {
            smsService.checkVerifyCode(contact, code);
        }

        return ResultVoUtil.success();
    }

    @PostMapping("forgotPassword")
    @ApiOperation(value = "忘记密码接口")
    public ResultVo forgotPasswd(@RequestParam("contact") String contact, @RequestParam("code") String code, @RequestParam("newPassword") String newPassword) {
        String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        if (contact.matches(EMAIL_REGEX)) {
            emailService.checkVerifyCode(contact, code);
        } else {
            smsService.checkVerifyCode(contact, code);
        }
        userService.forgotPassword(contact, newPassword);
        return ResultVoUtil.success();
    }
//    @PostMapping("register")
////    @ApiOperation("注册")
//    public R register(@RequestBody RegisterForm form) {
//        //表单校验
//        ValidatorUtils.validateEntity(form);
//
//        UserEntity user = new UserEntity();
//        user.setMobile(form.getMobile());
//        user.setUsername(form.getMobile());
//        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
//        user.setCreateTime(new Date());
//        userService.save(user);
//
//        return R.ok();
//    }
}
